package com.culture.bootdemo.utils;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * @Author: wenjl
 * @Date: 2021/7/2 14:48
 * @Description:
 */
public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {


    /**
     * 获取百分比,保留两位小数
     *
     * @param amount
     * @return #.##%
     */
    public static String getPercent(Integer amount) {
        if (null == amount) {
            return null;
        }
        return (new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toPlainString()) + "%";
    }


    /**
     * 获取金额-> int转String 除以100保留两位小数
     *
     * @param amount
     * @return #.##
     */
    public static String getAmountString(Integer amount) {
        if (null == amount) {
            return null;
        }
        return (new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toPlainString());
    }

    /**
     * 获取百分比
     *
     * @param x 除数
     * @param y 被除数
     * @return #.##%
     */
    public static String getPercent(Integer x, Integer y) {
        if (null == x || null == y || y.equals(0)) {
            return null;
        }
        BigDecimal divide = new BigDecimal(String.valueOf(x)).divide(new BigDecimal(String.valueOf(y)), 4, BigDecimal.ROUND_HALF_UP);
        BigDecimal multiply = divide.multiply(new BigDecimal("100"));
        return multiply.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "%";
    }

    /**
     * 省掉小数点后面的0
     *
     * @param val
     * @return
     */
    public static BigDecimal stripTrailingZeros(String val) {
        BigDecimal a = new BigDecimal("2.300");
        //省掉小数点末位的0
        BigDecimal bigDecimal = a.stripTrailingZeros();
        return bigDecimal;
    }

    /**
     * 数值格式化
     */
    public static void formatValue() {

//        NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CANADA); //建立货币格式化引用
        NumberFormat currency = NumberFormat.getCurrencyInstance(); //建立货币格式化引用
        currency.setMaximumFractionDigits(2);

        NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用
        percent.setMaximumFractionDigits(3); //设置百分比小数位数

        BigDecimal loanAmount = new BigDecimal("15000.486"); //贷款金额
        BigDecimal interestRate = new BigDecimal("0.008356"); //利率
        BigDecimal interest = loanAmount.multiply(interestRate); //相乘

        System.out.println("贷款金额:\t" + currency.format(loanAmount));
        System.out.println("利率:\t" + percent.format(interestRate));
        System.out.println("利息:\t" + currency.format(interest));
    }

    public static void main(String[] args) {
        formatValue();
    }
}
